/*
 *
 *  Copyright (C) 2009 GSyC/LibreSoft
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see http://www.gnu.org/licenses/. 
 *
 *  Author : Roberto Calvo Palomino <rocapal@gsyc.es>
 *  		 Raúl Román <rroman@gsyc.es>
 *
 */

package com.LibreGeoSocial.App.Utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLSession;
import javax.net.ssl.TrustManager;

import android.util.Log;

public class FacebookHandler {

	private String m_email;
	private String m_password;
	
	private static TrustManager[] trustManagers;
	
	public FacebookHandler (String email, String password)
	{
		m_email = email;
		m_password = password;
		
	}
	
	public boolean connect ()
	{
		Boolean ret = true;
		HttpsURLConnection urlConn;
		URL url;
		String FBLoginURL = "https://login.facebook.com/login.php?m&next=http://m.facebook.com/home.php";
        
		allowAllSSL();
		
        try {
        	
        	url = new URL(FBLoginURL);
			
			urlConn = (HttpsURLConnection) url.openConnection();
			
			// set Post method
	        urlConn.setDoOutput (true);
	        
	        // setting headers
	        urlConn.setRequestMethod("POST");
	        urlConn.setRequestProperty("Content-type", "application/x-www-form-urlencoded");       
	        urlConn.setRequestProperty("Accept-Encoding", "gzip, deflate");
	        urlConn.setRequestProperty("Host", "login.facebook.com");  
            urlConn.setRequestProperty("Connection", "Keep-Alive");
			
			// making content
	        String data = "email=" + m_email + 
	        				"&pass="+ m_password +
	        				"&login=Login";
	        
	        // writing content
			OutputStreamWriter out = new OutputStreamWriter(urlConn.getOutputStream());
			out.write (data);
			out.flush();
			
			// getting response
			
			BufferedReader in = new BufferedReader(
					new InputStreamReader(
							urlConn.getInputStream()));
			
			int status = urlConn.getResponseCode();
			
			if (status==302)
				ret = true;
			else
				ret = false;
			
			out.close();
			in.close();
			
		} catch (MalformedURLException e) {
			Log.e("Facebook",e.getMessage());
			return false;
		} catch (IOException e) {
			Log.e("Facebook",e.getMessage());
			return false;
		}
    
		
		return ret;
	}
	
	
	public static void allowAllSSL(){
		javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(new HostnameVerifier(){

			public boolean verify(String hostname, SSLSession session) {
				// TODO Auto-generated method stub
				return true;
			}
			
		});
		
		javax.net.ssl.SSLContext context = null;
		
		if(trustManagers==null){
			trustManagers = new javax.net.ssl.TrustManager[]{new _FakeX509TrustManager()};
		}
		
		try{
			context = javax.net.ssl.SSLContext.getInstance("TLS");
			context.init(null, trustManagers, new SecureRandom());
			
		}catch(NoSuchAlgorithmException e){
			Log.e("allowAllSSL", e.toString());
		}catch(KeyManagementException e){
			Log.e("allowAllSSL", e.toString());
		}
		
		javax.net.ssl.HttpsURLConnection.setDefaultSSLSocketFactory(context.getSocketFactory());
		
	}
	
	public static class _FakeX509TrustManager implements javax.net.ssl.X509TrustManager{
		
		private static final X509Certificate[] _AcceptedIssuers = new X509Certificate[]{};
		
		public void checkClientTrusted(X509Certificate[] chain, String authType)
				throws CertificateException {
			// TODO Auto-generated method stub
			
		}

		public void checkServerTrusted(X509Certificate[] chain, String authType)
				throws CertificateException {
			// TODO Auto-generated method stub
			
		}
		
		public boolean isClientTrusted(X509Certificate[] chain){
			return true;
		}
		
		public boolean isServerTrusted(X509Certificate[] chain){
			return true;
		}
		
		public X509Certificate[] getAcceptedIssuers() {
			// TODO Auto-generated method stub
			return _AcceptedIssuers;
		}
		
	}
}
